package com.study.example.gameserver.admin.recharge;


import com.sparrow.common.util.JsonUtil;
import com.sparrow.common.util.PlayerHelper;
import com.sparrow.common.util.SignUtil;
import com.sparrow.common.util.StringUtil;
import com.sparrow.socket.http.anno.HttpMethod;
import com.sparrow.socket.http.anno.HttpPacketClass;
import com.sparrow.socket.http.anno.HttpParam;
import com.sparrow.socket.http.bean.HttpResponse;
import com.sparrow.example_message.PacketId;
import com.study.example.gameserver.admin.recharge.domain.RechargeExtData;
import com.study.example.gameserver.base.ConfigService;
import com.study.example.gameserver.module.player.manager.PlayerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * 游戏服充值发货接口
 * 测试示例：
 * curl
 http://localhost:8080/?packetId=104&playerId=10000000001&orderId=1&amount=60&account=a&server=1&money=6&extData=%7B%22type%22%3A1%2C%22configId%22%3A1%7D&sign=39927e821225371da6e7b687f3b0e6c0
 */
@Component
@HttpPacketClass
public class RechargeHttpController {

    private static final Logger logger = LoggerFactory.getLogger(RechargeHttpController.class);

    @Autowired
    RechargeService rechargeService;
    @Autowired
    PlayerManager playerManager;
    @Autowired
    private ConfigService configService;
    /**
     * 后台充值发货接口
     */
    @HttpMethod(packetId = PacketId.Admin.REQ_ADMIN_RECHARGE, result = {})
    public CompletableFuture<HttpResponse> recharge(
            @HttpParam(name = "orderId", type = String.class) String orderId,
            @HttpParam(name = "account", type = String.class) String account,
            @HttpParam(name = "server", type = Integer.class) Integer serverId,
            @HttpParam(name = "playerId", type = Long.class) Long playerId,
            @HttpParam(name = "money", type = Integer.class) Integer money,
            //扩展数据 具体充值类型:具体充值类型配置id
            @HttpParam(name = "extData", type = String.class) String extData,
            @HttpParam(name = "sign", type = String.class) String sign)
    {

        logger.info("收到充值请求: orderId={}, accountId={}, serverId={}, playerId={}, money={}",
                orderId, account, serverId, playerId, money);

        HttpResponse response = new HttpResponse(PacketId.Admin.REQ_ADMIN_RECHARGE);

        // 参数校验
        if (orderId == null || account == null || serverId == null || playerId == null
                || money == null || money <= 0 || extData == null) {
            logger.error("参数错误, orderId={}, accountId={}, serverId={}, playerId={}, money={}, extData={}",
                    orderId, account, serverId, playerId, money, extData);
            return rechargeService.rechargeFail(response, "参数错误");
        }

        // 防止重复发货
        if (rechargeService.isOrderProcessed(orderId)) {
            logger.error("重复发货请求：orderId={}, playerId={}, accountId={}, serverId={}",
                    orderId, playerId, account, serverId);
            return rechargeService.rechargeFail(response, "订单重复");
        }
        // 验证扩展数据
        RechargeExtData rechargeExtData = null;
        if (extData != null && !extData.isEmpty()) {
            try {
                rechargeExtData = JsonUtil.parse(extData, RechargeExtData.class);
            } catch (Exception e) {
                logger.error("extData解析失败: {}", extData, e);
                return rechargeService.rechargeFail(response, "extData格式错误");
            }
        }
        // 验证玩家id
        String accountKey = PlayerHelper.toAccountKey(account, serverId);
        Long tarPlayerId = playerManager.getPlayerIdByAccountKey(accountKey);
        if (tarPlayerId == null || !tarPlayerId.equals(playerId)) {
            logger.error("账号关联playerId异常，服务器playerId:{} 参数playerId:{}", tarPlayerId, playerId);
            return rechargeService.rechargeFail(response, "账号关联playerId异常");
        }
        if (StringUtil.isEmpty(sign)) {
            return rechargeService.rechargeFail(response, "请求非法 sign is null");
        }
        //签名防止伪造充值发货
        String raw = String.format("orderId=%s&account=%s&server=%d&playerId=%d&money=%d",
                orderId, account, serverId, playerId, money);
        String serverSign = SignUtil.generateSign(raw, configService.getAppKey());
        if (!serverSign.equals(sign)) {
            return rechargeService.rechargeFail(response, "签名异常");
        }
        // 执行发货逻辑
        CompletableFuture<HttpResponse> future = rechargeService.recharge(orderId, account, serverId, playerId, money, rechargeExtData, response);
        return future;
    }
}

